package com.bsh.utils.jpush;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

/**
 * 推送工具
 * @author gsh
 *	
 * 推送,app端数据结构： ====extras 中放入3个数据=== 
 * type:0 说明： 0 普通通知 1带url的链接 2公告消息(消息列表)
 * url:"http://api.bshbsh.cn/xxxxxxx" 说明： type为1时此字段有值
 * logo:"http://api.bshbsh.cn/aa.png" 说明： 收到消息后，创建自定义通知用到的图标。如无，用app图标
 * 内容部分无特殊说明，请直接展示	 
 */
@Component
@Lazy(false)
public class JpushMessageSender {
	private static Logger log = LoggerFactory.getLogger(JpushMessageSender.class);
	
	@Value("${jpush.MASTER_SECRET}")
	String MASTER_SECRET;
	@Value("${jpush.APP_KEY}")
	String APP_KEY;	
	
	/**
	 * 发送给全部,msg中设置jpsid 时发送给指定用户
	 * @param msg
	 */
	public void Send(JpushMessage msg){		
		SendToAndroid(msg);
		SendToIOS(msg);
	}
	
	/**
	 * 仅发送给android
	 * @param msg
	 */
	public void SendToAndroid(JpushMessage msg) {
		PushPayload payloadAnd = buildPushObject_android(msg);
		SendPush(msg,payloadAnd);
	}
	
	/**
	 * 发送给IOS
	 * @param msg
	 */
	public void SendToIOS(JpushMessage msg) {
		PushPayload payloadIos = buildPushObject_ios(msg);
		SendPush(msg,payloadIos);
	}
	
	@SuppressWarnings("deprecation")
	private void SendPush(JpushMessage msg,PushPayload payload) {
		JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, 3);	
		
		try {
			PushResult result = jpushClient.sendPush(payload);
		} catch (APIConnectionException e) {
			log.error("连接到极光服务器错误，请稍后重试", e);

		} catch (APIRequestException e) {
			log.error("Error response from JPush server. Should review and fix it. ", e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Code: " + e.getErrorCode());
			log.info("Error Message: " + e.getErrorMessage());
			log.info("Msg ID: " + e.getMsgId());
		}
	}

	private PushPayload buildPushObject_android(JpushMessage msg) {
		Builder builder =  PushPayload.newBuilder();
		builder.setPlatform(Platform.android());
		if(!StringUtils.isEmpty(msg.getJpsid())){
			builder.setAudience(Audience.registrationId(msg.getJpsid()));  
		}else{
			builder.setAudience(Audience.all());
		}    
		builder.setNotification(Notification.newBuilder()
						.addPlatformNotification(AndroidNotification.newBuilder() 
								.setTitle(msg.getTitle())
								.setAlert(msg.getAlert())
		                        .addExtra("title",StringUtils.isEmpty(msg.getTitle())?"":msg.getTitle())
		                        .addExtra("alert",StringUtils.isEmpty(msg.getAlert())?"":msg.getAlert())
		                        .addExtra("type", StringUtils.isEmpty(msg.getType())?"":msg.getType()) 
		                        .addExtra("url",StringUtils.isEmpty(msg.getUrl())?"":msg.getUrl())
								.addExtra("logo", StringUtils.isEmpty(msg.getLogo())?"":msg.getLogo()).build()
						 )
						.build())
				.setMessage(
						Message.newBuilder()
                        .setMsgContent(msg.getContent())
                        .setContentType(msg.getType())
                        .addExtra("title",StringUtils.isEmpty(msg.getTitle())?"":msg.getTitle())
                        .addExtra("alert",StringUtils.isEmpty(msg.getAlert())?"":msg.getAlert())
                        .addExtra("type", StringUtils.isEmpty(msg.getType())?"":msg.getType()) 
                        .addExtra("url",StringUtils.isEmpty(msg.getUrl())?"":msg.getUrl())
						.addExtra("logo", StringUtils.isEmpty(msg.getLogo())?"":msg.getLogo()).build()                        						
						).setOptions(Options.newBuilder().setApnsProduction(true) 
						.build());
		return builder.build();
	}

	private PushPayload buildPushObject_ios(JpushMessage msg) {
		Builder builder =  PushPayload.newBuilder();
		builder.setPlatform(Platform.ios());
		if(!StringUtils.isEmpty(msg.getJpsid())){
			builder.setAudience(Audience.registrationId(msg.getJpsid()));   
		}else{
			builder.setAudience(Audience.all());
		}   
		builder.setNotification(Notification.newBuilder()
						.addPlatformNotification(IosNotification.newBuilder() 
								//.setTitle(msg.getTitle())
								.setAlert(msg.getAlert())
		                        .addExtra("title",StringUtils.isEmpty(msg.getTitle())?"":msg.getTitle())
		                        .addExtra("alert",StringUtils.isEmpty(msg.getAlert())?"":msg.getAlert())
		                        .addExtra("type", StringUtils.isEmpty(msg.getType())?"":msg.getType()) 
		                        .addExtra("url",StringUtils.isEmpty(msg.getUrl())?"":msg.getUrl())
								.addExtra("logo", StringUtils.isEmpty(msg.getLogo())?"":msg.getLogo()).build()
						)		
						.build())
				.setMessage(
						Message.newBuilder()
                        .setMsgContent(msg.getContent())
                        .setContentType(msg.getType())
                        .addExtra("title",StringUtils.isEmpty(msg.getTitle())?"":msg.getTitle())
                        .addExtra("alert",StringUtils.isEmpty(msg.getAlert())?"":msg.getAlert())
                        .addExtra("type", StringUtils.isEmpty(msg.getType())?"":msg.getType()) 
                        .addExtra("url",StringUtils.isEmpty(msg.getUrl())?"":msg.getUrl())
						.addExtra("logo", StringUtils.isEmpty(msg.getLogo())?"":msg.getLogo()).build()                         						
						).setOptions(Options.newBuilder().setApnsProduction(true) 
						.build());
		return builder.build();
	}
}
